package com.example.sanguogameserver.util;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import com.example.sanguogameserver.consts.RedisKeyConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Map;

@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void setObject(String key, Object value) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
    }
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void setObject(String key, Object value, Duration duration) {
        redisTemplate.opsForValue().set(key, JSON.toJSONString(value), duration);
    }

    public <T> T getObj(String key, Class<T> t) {
        String strResult = redisTemplate.opsForValue().get(key);
        return JSON.parseObject(strResult, t);
    }

    public void putHash(String key, Object hashKey, Object value) {
        redisTemplate.opsForHash().put(key, Convert.toStr(hashKey), JSON.toJSONString(value));
    }

    public void putHash(String key, Object hashKey, Object value, Duration duration) {
        redisTemplate.opsForHash().put(key, Convert.toStr(hashKey), JSON.toJSONString(value));
        setDeleteHashDuration(key, duration);
    }

    public void setDeleteHashDuration(String key, Duration duration) {
        setObject(RedisKeyConst.DeleteHash.name() + key, "1", duration);
    }
    public void deleteHashDuration(String key) {
        delete(RedisKeyConst.DeleteHash.name() + key);
    }

    public <T> T getHash(String key, Object hashKey, Class<T> t) {
        String strResult = (String) redisTemplate.opsForHash().get(key, Convert.toStr(hashKey));
        return JSON.parseObject(strResult, t);
    }

    public Map<Object, Object> entries(String key) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);
        return entries;
    }

    public void deleteHash(String key, Object hashKey) {
        redisTemplate.opsForHash().delete(key, Convert.toStr(hashKey));
        deleteHashDuration(key);
    }
}
